import { XiangqiGame } from './game.js';
import { COLORS, GAME_STATUS, AI_DIFFICULTY } from './constants.js';

// 游戏主程序类
class XiangqiApp {
    constructor() {
        this.game = new XiangqiGame();
        this.canvas = document.getElementById('chessBoard');
        this.ctx = this.canvas.getContext('2d');
        
        // 绑定DOM元素
        this.startBtn = document.getElementById('startBtn');
        this.pauseBtn = document.getElementById('pauseBtn');
        this.resumeBtn = document.getElementById('resumeBtn');
        this.undoBtn = document.getElementById('undoBtn');
        this.restartBtn = document.getElementById('restartBtn');
        this.gameStatusEl = document.getElementById('gameStatus');
        this.currentTurnEl = document.getElementById('currentTurn');
        this.redScoreEl = document.getElementById('redScore');
        this.blackScoreEl = document.getElementById('blackScore');
        this.aiDifficultySelect = document.getElementById('aiDifficulty');
        this.gameModeRadios = document.getElementsByName('gameMode');
        
        // 初始化事件监听
        this.initEventListeners();
        
        // 调整画布大小
        this.resizeCanvas();
        
        // 初始绘制
        this.draw();
        
        // 更新UI状态
        this.updateUI();
    }
    
    // 初始化事件监听
    initEventListeners() {
        // 按钮事件监听
        this.startBtn.addEventListener('click', () => this.handleStart());
        this.pauseBtn.addEventListener('click', () => this.handlePause());
        this.resumeBtn.addEventListener('click', () => this.handleResume());
        this.undoBtn.addEventListener('click', () => this.handleUndo());
        this.restartBtn.addEventListener('click', () => this.handleRestart());
        
        // 游戏模式切换
        this.gameModeRadios.forEach(radio => {
            radio.addEventListener('change', (e) => this.handleGameModeChange(e.target.value));
        });
        
        // AI难度调整
        this.aiDifficultySelect.addEventListener('change', () => {
            this.game.setAIDifficulty(this.aiDifficultySelect.value);
        });
        
        // 棋盘点击事件
        this.canvas.addEventListener('click', (e) => this.handleBoardClick(e));
        
        // 窗口大小变化时调整画布
        window.addEventListener('resize', () => this.resizeCanvas());
    }
    
    // 调整画布大小以适应屏幕
    resizeCanvas() {
        const container = this.canvas.parentElement;
        const maxWidth = container.clientWidth - 40; // 减去内边距
        const maxHeight = window.innerHeight - 200; // 留出足够空间给其他元素
        
        // 保持棋盘比例
        const aspectRatio = 9 / 10; // 象棋棋盘比例
        let newWidth = maxWidth;
        let newHeight = newWidth / aspectRatio;
        
        if (newHeight > maxHeight) {
            newHeight = maxHeight;
            newWidth = newHeight * aspectRatio;
        }
        
        // 设置画布大小
        this.canvas.width = newWidth;
        this.canvas.height = newHeight;
        
        // 重新绘制
        this.draw();
    }
    
    // 处理开始游戏
    handleStart() {
        if (this.game.start()) {
            this.updateUI();
            this.draw();
        }
    }
    
    // 处理暂停游戏
    handlePause() {
        if (this.game.pause()) {
            this.updateUI();
        }
    }
    
    // 处理继续游戏
    handleResume() {
        if (this.game.resume()) {
            this.updateUI();
        }
    }
    
    // 处理悔棋
    handleUndo() {
        if (this.game.undo()) {
            this.updateUI();
            this.draw();
        }
    }
    
    // 处理重新开始
    handleRestart() {
        if (this.game.restart()) {
            this.updateUI();
            this.draw();
        }
    }
    
    // 处理游戏模式变化
    handleGameModeChange(mode) {
        if (this.game.setGameMode(mode)) {
            this.updateUI();
            // 更新AI难度选择器的可见性
            const aiDifficultySection = document.querySelector('.ai-difficulty');
            aiDifficultySection.style.display = mode === 'human-ai' ? 'block' : 'none';
        }
    }
    
    // 处理棋盘点击
    handleBoardClick(e) {
        // 获取相对于画布的坐标
        const rect = this.canvas.getBoundingClientRect();
        const x = e.clientX - rect.left;
        const y = e.clientY - rect.top;
        
        // 将坐标转换为棋盘位置
        const boardPos = this.canvasToBoard(x, y);
        
        if (boardPos) {
            // 处理棋子选择或移动
            if (this.game.selectPiece(boardPos.row, boardPos.col)) {
                this.draw();
                this.updateUI();
            }
        }
    }
    
    // 将画布坐标转换为棋盘位置
    canvasToBoard(x, y) {
        const boardWidth = this.canvas.width;
        const boardHeight = this.canvas.height;
        
        // 计算实际单元格大小和边距
        const cellSize = Math.min(
            boardWidth / 8,  // 9列有8个间隔
            boardHeight / 10 // 10行有10个间隔
        );
        const marginX = (boardWidth - cellSize * 8) / 2;
        const marginY = (boardHeight - cellSize * 10) / 2;
        
        // 计算棋盘位置
        const col = Math.round((x - marginX) / cellSize);
        const row = Math.round((y - marginY) / cellSize);
        
        // 检查是否在有效范围内
        if (row >= 0 && row < 10 && col >= 0 && col < 9) {
            return { row, col };
        }
        
        return null;
    }
    
    // 更新UI状态
    updateUI() {
        const gameInfo = this.game.getGameInfo();
        
        // 更新游戏状态显示
        switch (gameInfo.status) {
            case GAME_STATUS.READY:
                this.gameStatusEl.textContent = '准备开始';
                break;
            case GAME_STATUS.PLAYING:
                this.gameStatusEl.textContent = gameInfo.isInCheck[gameInfo.currentTurn] 
                    ? '将军!' : '游戏进行中';
                break;
            case GAME_STATUS.PAUSED:
                this.gameStatusEl.textContent = '游戏暂停';
                break;
            case GAME_STATUS.OVER:
                this.gameStatusEl.textContent = 
                    gameInfo.winner === COLORS.RED ? '红方胜利!' : '黑方胜利!';
                break;
            case GAME_STATUS.DRAW:
                this.gameStatusEl.textContent = '和棋!';
                break;
        }
        
        // 更新当前回合显示
        this.currentTurnEl.textContent = 
            gameInfo.currentTurn === COLORS.RED ? '红方回合' : '黑方回合';
        this.currentTurnEl.style.color = 
            gameInfo.currentTurn === COLORS.RED ? '#8B0000' : '#343A40';
        
        // 更新分数显示
        this.redScoreEl.textContent = gameInfo.scores[COLORS.RED];
        this.blackScoreEl.textContent = gameInfo.scores[COLORS.BLACK];
        
        // 更新按钮状态
        this.startBtn.disabled = gameInfo.status === GAME_STATUS.PLAYING;
        this.pauseBtn.disabled = gameInfo.status !== GAME_STATUS.PLAYING;
        this.resumeBtn.disabled = gameInfo.status !== GAME_STATUS.PAUSED;
        this.undoBtn.disabled = gameInfo.status !== GAME_STATUS.PLAYING;
        
        // 更新游戏模式单选按钮
        this.gameModeRadios.forEach(radio => {
            radio.disabled = gameInfo.status === GAME_STATUS.PLAYING;
            if (radio.value === gameInfo.gameMode) {
                radio.checked = true;
            }
        });
        
        // 更新AI难度选择器
        this.aiDifficultySelect.disabled = 
            gameInfo.status === GAME_STATUS.PLAYING || 
            gameInfo.gameMode !== 'human-ai';
    }
    
    // 绘制游戏
    draw() {
        // 清空画布
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        
        const boardWidth = this.canvas.width;
        const boardHeight = this.canvas.height;
        
        // 计算实际单元格大小和边距
        const cellSize = Math.min(
            boardWidth / 8,  // 9列有8个间隔
            boardHeight / 10 // 10行有10个间隔
        );
        const marginX = (boardWidth - cellSize * 8) / 2;
        const marginY = (boardHeight - cellSize * 10) / 2;
        
        // 绘制棋盘背景
        this.ctx.fillStyle = '#E8C57A';
        this.ctx.fillRect(marginX, marginY, cellSize * 8, cellSize * 10);
        
        // 绘制棋盘线条
        this.ctx.strokeStyle = '#000';
        this.ctx.lineWidth = 1;
        
        // 绘制横线
        for (let i = 0; i <= 10; i++) {
            this.ctx.beginPath();
            this.ctx.moveTo(marginX, marginY + i * cellSize);
            this.ctx.lineTo(marginX + cellSize * 8, marginY + i * cellSize);
            this.ctx.stroke();
        }
        
        // 绘制竖线
        for (let i = 0; i < 9; i++) {
            this.ctx.beginPath();
            // 河界部分的竖线断开
            if (i === 0 || i === 8) {
                // 两边的边线完整
                this.ctx.moveTo(marginX + i * cellSize, marginY);
                this.ctx.lineTo(marginX + i * cellSize, marginY + cellSize * 10);
            } else {
                // 中间的线在河界断开
                this.ctx.moveTo(marginX + i * cellSize, marginY);
                this.ctx.lineTo(marginX + i * cellSize, marginY + cellSize * 4);
                this.ctx.moveTo(marginX + i * cellSize, marginY + cellSize * 5);
                this.ctx.lineTo(marginX + i * cellSize, marginY + cellSize * 10);
            }
            this.ctx.stroke();
        }
        
        // 绘制河界
        this.ctx.font = `${cellSize * 0.3}px Microsoft YaHei`;
        this.ctx.fillStyle = '#8B0000';
        this.ctx.textAlign = 'center';
        this.ctx.fillText('楚 河', marginX + cellSize * 2, marginY + cellSize * 4.5);
        this.ctx.fillText('汉 界', marginX + cellSize * 6, marginY + cellSize * 4.5);
        
        // 绘制九宫格斜线
        // 红方九宫格
        this.ctx.beginPath();
        this.ctx.moveTo(marginX + cellSize * 3, marginY);
        this.ctx.lineTo(marginX + cellSize * 5, marginY + cellSize * 2);
        this.ctx.moveTo(marginX + cellSize * 5, marginY);
        this.ctx.lineTo(marginX + cellSize * 3, marginY + cellSize * 2);
        this.ctx.stroke();
        
        // 黑方九宫格
        this.ctx.beginPath();
        this.ctx.moveTo(marginX + cellSize * 3, marginY + cellSize * 7);
        this.ctx.lineTo(marginX + cellSize * 5, marginY + cellSize * 9);
        this.ctx.moveTo(marginX + cellSize * 5, marginY + cellSize * 7);
        this.ctx.lineTo(marginX + cellSize * 3, marginY + cellSize * 9);
        this.ctx.stroke();
        
        // 绘制棋子
        const gameInfo = this.game.getGameInfo();
        
        // 遍历棋盘绘制棋子
        for (let row = 0; row < 10; row++) {
            for (let col = 0; col < 9; col++) {
                const piece = this.game.board.getPieceAt(row, col);
                if (piece) {
                    this.drawPiece(piece, row, col, marginX, marginY, cellSize);
                }
            }
        }
        
        // 绘制选中状态
        if (this.game.selectedPiece) {
            this.drawSelectedPiece(
                this.game.selectedPiece.row,
                this.game.selectedPiece.col,
                marginX, marginY, cellSize
            );
            
            // 绘制可能的移动位置
            this.game.possibleMoves.forEach(move => {
                this.drawPossibleMove(move.row, move.col, marginX, marginY, cellSize);
            });
        }
        
        // 绘制将军警告
        if (gameInfo.isInCheck[COLORS.RED] || gameInfo.isInCheck[COLORS.BLACK]) {
            const generalColor = gameInfo.isInCheck[COLORS.RED] ? COLORS.RED : COLORS.BLACK;
            const general = this.game.board.findGeneral(generalColor);
            if (general) {
                this.drawCheckWarning(general.row, general.col, marginX, marginY, cellSize);
            }
        }
    }
    
    // 绘制棋子
    drawPiece(piece, row, col, marginX, marginY, cellSize) {
        const x = marginX + col * cellSize;
        const y = marginY + row * cellSize;
        const radius = cellSize * 0.4;
        
        // 绘制棋子底色
        this.ctx.fillStyle = piece.color === COLORS.RED ? '#F8D7DA' : '#343A40';
        this.ctx.beginPath();
        this.ctx.arc(x, y, radius, 0, Math.PI * 2);
        this.ctx.fill();
        
        // 绘制棋子边框
        this.ctx.strokeStyle = '#000';
        this.ctx.lineWidth = 2;
        this.ctx.stroke();
        
        // 绘制棋子文字
        this.ctx.font = `bold ${cellSize * 0.4}px Microsoft YaHei`;
        this.ctx.fillStyle = piece.color === COLORS.RED ? '#8B0000' : '#fff';
        this.ctx.textAlign = 'center';
        this.ctx.textBaseline = 'middle';
        this.ctx.fillText(piece.getChineseName(), x, y);
    }
    
    // 绘制选中棋子高亮
    drawSelectedPiece(row, col, marginX, marginY, cellSize) {
        const x = marginX + col * cellSize;
        const y = marginY + row * cellSize;
        const radius = cellSize * 0.45;
        
        // 绘制选中高亮
        this.ctx.strokeStyle = '#FFD700';
        this.ctx.lineWidth = 3;
        this.ctx.beginPath();
        this.ctx.arc(x, y, radius, 0, Math.PI * 2);
        this.ctx.stroke();
    }
    
    // 绘制可能的移动位置
    drawPossibleMove(row, col, marginX, marginY, cellSize) {
        const x = marginX + col * cellSize;
        const y = marginY + row * cellSize;
        const radius = cellSize * 0.2;
        
        // 检查目标位置是否有对方棋子
        const targetPiece = this.game.board.getPieceAt(row, col);
        if (targetPiece && targetPiece.color !== this.game.currentTurn) {
            // 有对方棋子，绘制吃子标记（圆环）
            this.ctx.strokeStyle = 'rgba(255, 215, 0, 0.7)';
            this.ctx.lineWidth = 3;
            this.ctx.beginPath();
            this.ctx.arc(x, y, cellSize * 0.35, 0, Math.PI * 2);
            this.ctx.stroke();
        } else {
            // 无棋子，绘制移动标记（圆点）
            this.ctx.fillStyle = 'rgba(255, 215, 0, 0.5)';
            this.ctx.beginPath();
            this.ctx.arc(x, y, radius, 0, Math.PI * 2);
            this.ctx.fill();
        }
    }
    
    // 绘制将军警告
    drawCheckWarning(row, col, marginX, marginY, cellSize) {
        const x = marginX + col * cellSize;
        const y = marginY + row * cellSize;
        const radius = cellSize * 0.5;
        
        // 绘制闪烁的红色边框表示将军
        this.ctx.strokeStyle = '#FF0000';
        this.ctx.lineWidth = 4;
        this.ctx.beginPath();
        this.ctx.arc(x, y, radius, 0, Math.PI * 2);
        this.ctx.stroke();
    }
}

// 当页面加载完成后初始化游戏
window.addEventListener('DOMContentLoaded', () => {
    const app = new XiangqiApp();
    // 将app实例暴露到window对象，方便调试
    window.xiangqiApp = app;
});